/*
 * Copyright (c) 2020 IUV Inc. All rights reserved.
 * 项目名称：IUV TXY
 * 文件名：ImAccountServiceImpl.java
 * Date：20-10-22 下午3:57
 * Author：Will
 */

package com.iuv.imdemo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iuv.config.ImSetting;
import com.iuv.imdemo.dto.ResultItem;
import com.iuv.imdemo.dto.UserItem;
import com.iuv.imdemo.service.ImAccountService;
import com.iuv.imdemo.util.ImRequsetUtil;
import com.tencentyun.TLSSigAPIv2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * IM例子-IM服务帐号管理业务实现类
 *
 * @author Will
 * @date 15:57
 */
@Service("imAccountService")
public class ImAccountServiceImpl implements ImAccountService {
    private final static Logger logger = LoggerFactory.getLogger(ImAccountServiceImpl.class);

    /**
     * 导入用户到IM服务
     *
     * @param userIdList
     */
    @Override
    public void importAccount(List<String> userIdList) {
        if (userIdList != null) {
            String userSig = genUserSig(ImSetting.IDENTIFIER);
            List<UserItem> checkItem = userIdList.stream().map(e -> new UserItem(e)).collect(Collectors.toList());
            List<ResultItem> accountCheckResultList = accountCheck(checkItem, userSig);
            if (accountCheckResultList != null && accountCheckResultList.size() > 0) {
                List<String> needImportUserIdList = new ArrayList<>();
                for (ResultItem resultItem : accountCheckResultList) {
                    if (resultItem.getAccountStatus().equalsIgnoreCase("NotImported")) {
                        needImportUserIdList.add(resultItem.getUserID());
                    } else {
                        logger.info("Account:" + resultItem.getUserID() + "已导入，无须重复！");
                    }
                }
                if (needImportUserIdList.size() > 0) {
                    JSONObject postData = new JSONObject();
                    postData.put("Accounts", needImportUserIdList);
                    JSONObject respond = ImRequsetUtil.request("v4/im_open_login_svc/multiaccount_import", userSig, postData.toJSONString());
                    if (respond != null) {
                        String actionStatus = (String) respond.get("ActionStatus");
                        if ("OK".equalsIgnoreCase(actionStatus)) {
                            logger.info("成功导入以下帐号：" + needImportUserIdList);
                        } else {
                            logger.warn("导入出错，原因是：" + respond.get("ErrorInfo"));
                        }
                    }
                }
            }
        }
    }

    /**
     * 根据用户ID生成UserSig
     *
     * @param userId
     * @return
     */
    @Override
    public String genUserSig(String userId) {
        TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(ImSetting.SDK_APP_ID, ImSetting.KEY);
        //单位为秒
        long expire = 24 * 60 * 60;
        return tlsSigAPIv2.genSig(userId, expire);
    }

    /**
     * 查询帐号
     *
     * @param checkItem
     * @return
     */
    private List<ResultItem> accountCheck(List<UserItem> checkItem, String userSig) {
        JSONObject postData = new JSONObject();
        postData.put("CheckItem", checkItem);
        JSONObject respond = ImRequsetUtil.request("v4/im_open_login_svc/account_check", userSig, postData.toJSONString());
        if (respond != null) {
            String actionStatus = (String) respond.get("ActionStatus");
            if ("OK".equalsIgnoreCase(actionStatus)) {
                return JSON.parseArray(JSON.toJSONString(respond.get("ResultItem")), ResultItem.class);
            }
        }
        return null;
    }

}
